home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6073 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  50 lines

  1. Path: news.th-darmstadt.de!news!enno
  2. From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Why use a reference on a ptr foo(int &*parm) as a formal parm ?
  5. Date: 11 Feb 1996 14:52:18 GMT
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Distribution: world
  8. Message-ID: <ENNO.96Feb11155218@kitz.inferenzsysteme.informatik.th-darmstadt.de>
  9. References: <311DC7A8.2A1C@worldcom.ch>
  10. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  11. In-reply-to: Jean-Pierre Schnyder's message of Sun, 11 Feb 1996 11:40:40 +0100
  12.  
  13. In article <311DC7A8.2A1C@worldcom.ch> Jean-Pierre Schnyder <jschnyde@worldcom.ch> writes:
  14.  
  15.    I'm not sure to understand the rationale for this technique. Any idea ?
  16.  
  17. Passing a non-const reference as argument is one way to perform a 'call by
  18. reference' in C++. Another way is to use a pointer to the appropriate type
  19. instead. An example might be helpful:
  20.  
  21. >>>>
  22. #include <iostream.h>
  23.  
  24. void alloc(int*& mem,int n) { mem=new int[n]; }
  25. void dealloc(int* mem) { delete[] mem; }
  26.  
  27. int main()
  28. {
  29.   int* ip;
  30.   alloc(ip,100);
  31.   dealloc(ip);
  32. }
  33. <<<<
  34.  
  35. The invocation of 'alloc' modifies the pointer 'ip'. Before the function
  36. call 'ip' points to nowhere, afterwards it points to the newly allocated
  37. integer array. If 'alloc' would be defined as
  38.  
  39.           void alloc(int* mem,int n) { mem=new int[n]; }
  40.  
  41. the local copy of the pointer value would be changed but not 'ip'.
  42. In contrast 'dealloc' doesn't need a to modify the pointer because it simply
  43. uses the pointer to free the allocated ressources.
  44.  
  45.     Enno
  46.  
  47. PS: a pointer to a reference is no valid type in C++.
  48. --
  49.     Enno
  50.